#include <fstream>
#include <iostream>
#include <sstream>
#include <boost/format.hpp>
#include "editor.hh"
#include "write_data.hh"
#include "read_data.hh"
#include "simple_reader.hh"

using namespace std;
using boost::format;

void edit(Adventure& adv, const std::string& command_line) {
  string com;
  string tmp;
  istringstream command_ss(command_line);
  string msg("ERROR");
  
  command_ss >> com;
  if(com == "") {
    cout << "*EMPTY COMMAND*\n";
  } else if(com == "save") {
    ofstream fout("GAMESAVE");
    msg = "OK";
  } else if(com == "load") {
    ifstream fin("GAMESAVE");
    msg = "OK";
  } else if(com == "verb") {
    int n;

    if(command_ss >> tmp >> n) {
      if(n < 0)
	adv.verbs.erase(tmp);
      else
	adv.verbs[tmp] = n;
      msg = str(format("Verb '%s' is now %d.") % tmp % n);
    }
  } else if(com == "msglist") {
    //write("msglist", adv.msgs, cout) << endl;
    write_msgs(adv, cout) << endl;
    msg = "OK";
  } else if(com == "write") {
    ofstream fout("GAMEDATA");
    write("Adventure", adv, fout) << endl;
    fout << '\x04';
    fout.close();
    msg = "OK";
  } else if(com == "read") {
    ifstream fin("GAMEDATA");
    string hdr(read_header(fin));
    if(hdr == "Adventure") {
      read(fin, adv);
      msg = "OK";
    } else {
      msg = "LOAD ERROR";
    }
  } else {
    cout << "Unknown command '" << com << "'!\n";
  }
  cout << msg << endl;
}

